package admin_controller

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/models"
	"cloud-navigation/app/services"
	"cloud-navigation/global"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 导航分类资源类
type Assort struct{}

// 按排序字段获取所有分类
func (assort Assort) Index(c *gin.Context) {
	var ass []models.Assort
	if err := global.App.DB.Order("sort").Find(&ass).Error; err != nil {
		response.BusinessFail(c, "查询失败")
		return
	}
	response.Success(c, ass)
}
func (assort Assort) Show(c *gin.Context) {
	var (
		uri request.Uri
		ass models.Assort
	)
	if err := c.ShouldBindUri(&uri); err != nil {
		response.BusinessFail(c, "参数错误")
		return
	}
	if err := global.App.DB.First(&ass, uri.Id).Error; err != nil {
		response.BusinessFail(c, "查询失败")
		return
	}
	response.Success(c, ass)
}

// 创建分类
func (assort Assort) Create(c *gin.Context) {
	var (
		ass   request.Assort
		model models.Assort
	)
	if !services.Request(c, &ass) {
		return
	}
	model = models.Assort{Name: ass.Name, Sort: uint8(ass.Sort)}
	err := global.App.DB.Create(&model).Error
	if err != nil {
		response.BusinessFail(c, "创建失败")
		return
	}
	services.WriteLogs(c, "创建导航分类: name="+ass.Name, 0)
	response.Success(c, &model)
}

// 更新分类
func (assort Assort) Update(c *gin.Context) {
	var (
		uri   request.Uri
		ass   request.Assort
		model models.Assort
	)
	if err := c.ShouldBindUri(&uri); err != nil {
		response.BusinessFail(c, "参数错误")
		return
	}
	if !services.Request(c, &ass) {
		return
	}
	model.ID.ID = uri.Id
	err := global.App.DB.Model(&model).Updates(ass).Error
	if err != nil {
		response.BusinessFail(c, "更新失败")
		return
	}
	services.WriteLogs(c, "更新导航分类: name="+ass.Name, 0)
	response.Success(c, &model)
}

// 删除分类
func (assort Assort) Delete(c *gin.Context) {
	var (
		uri request.Uri
	)
	if err := c.ShouldBindUri(&uri); err != nil {
		response.BusinessFail(c, "参数错误")
		return
	}
	if err := global.App.DB.Delete(&models.Assort{}, uri.Id).Error; err != nil {
		response.BusinessFail(c, "删除失败")
		return
	}
	services.WriteLogs(c, "删除导航分类: id="+strconv.FormatUint(uint64(uri.Id), 10), 0)
	response.Success(c, nil)
}
